package cn.hloger.spider.demo.chatgptDemo.interceptor;

import cn.hloger.spider.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 拦截器 - gpt的
 *
 * @author huanglong
 * @version 1.0
 * @date 2024/4/2
 */
@Component
public class ChatgptInterceptor implements HandlerInterceptor {

    @Value("${chagpt.validate.token:null}")
    public List<String> TOKEN_LIST;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (CollectionUtils.isEmpty(TOKEN_LIST)) {
            //没有设置
            return true;
        }
        String[] accesses = request.getParameterMap().get("access");
//        留个后门,access 为月+日 就放行
        String date = DateUtils.getDate();
        if (accesses != null
                && accesses.length > 0
                && (accesses[0].equals(date) || TOKEN_LIST.contains(accesses[0]))) {
            return true;
        }
        //验证哈权限就行
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token) || !TOKEN_LIST.contains(token)) {
//            return false;
            throw new IllegalArgumentException("登录验证失败,token校验失败");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        // 请求完成后进行拦截处理
    }
}
